#pragma once
#ifndef GLOBAL_H
#define GLOBAL_H
#if defined(_MSC_VER) && (_MSC_VER >= 1600)
# pragma execution_character_set("utf-8")
#endif

/*! 全局变量 */

#include <Windows.h>


#include <string>
#include <vector>
#include <map>
#include <memory> // unique_ptr

#include <QObject>
#include <QDebug>


#define wchar_to_utf8_no_alloc(wsrc, dest, dest_size) \
    WideCharToMultiByte(CP_UTF8, 0, wsrc, -1, dest, dest_size, NULL, NULL)
#define utf8_to_wchar_no_alloc(src, wdest, wdest_size) \
    MultiByteToWideChar(CP_UTF8, 0, src, -1, wdest, wdest_size)
#define sfree(p) do {if (p != NULL) {free((void*)(p)); p = NULL;}} while(0)
#define wconvert(p)     wchar_t* w ## p = utf8_to_wchar(p)
#define walloc(p, size) wchar_t* w ## p = (p == NULL)?NULL:(wchar_t*)calloc(size, sizeof(wchar_t))
#define wfree(p) sfree(w ## p)

/*
 * Converts an UTF8 string to UTF-16 (allocate returned string)
 * Returns NULL on error
 */
static wchar_t* utf8_to_wchar(const char* str)
{
    int size = 0;
    wchar_t* wstr = NULL;

    if (str == NULL)
        return NULL;

    // Convert the empty string too
    if (str[0] == 0)
        return (wchar_t*)calloc(1, sizeof(wchar_t));

    // Find out the size we need to allocate for our converted string
    size = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
    if (size <= 1)	// An empty string would be size 1
        return NULL;

    if ((wstr = (wchar_t*)calloc(size, sizeof(wchar_t))) == NULL)
        return NULL;

    if (utf8_to_wchar_no_alloc(str, wstr, size) != size) {
        sfree(wstr);
        return NULL;
    }
    return wstr;
}

/*
 * Converts an UTF-16 string to UTF8 (allocate returned string)
 * Returns NULL on error
 */
static char* wchar_to_utf8(const wchar_t* wstr)
{
    int size = 0;
    char* str = NULL;

    // Convert the empty string too
    if (wstr[0] == 0)
        return (char*)calloc(1, 1);

    // Find out the size we need to allocate for our converted string
    size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
    if (size <= 1)	// An empty string would be size 1
        return NULL;

    if ((str = (char*)calloc(size, 1)) == nullptr)
        return NULL;

    if (wchar_to_utf8_no_alloc(wstr, str, size) != size) {
        sfree(str);
        return NULL;
    }

    return str;
}




















#endif // GLOBAL_H
